/* 批量冻结与解冻页
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \src\pages\QuotaManage\QuotaAdjust\component\BatchFreeze.tsx
 * @Date: 2021-08-31 09:39:33
 * @LastEditTime: 2021-09-14 16:34:43
 */
import React, { createRef } from 'react'
import { UdTable, http, validators, UdForm } from '@/lib'
import UdUploader from '@/components/UdUploader/Uploader'
import { Input, Select, message, Tooltip } from 'antd'
import quotaApis from '@/apis/AboutQuota'
import todoApi from '@/apis/TodoList/index'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import QuotaApprove from '@/components/getQuotaApprove'
const { TextArea } = Input
const { Option } = Select

/** 列表项类型定义 */
interface DataSourceItem {
  frozenStatus: number
  frozenStatusWay: number
  [Key: string]: any
}
export default class BatchFreeze extends React.Component<IProps, IState> {
  private form: WrappedFormUtils
  private FROZEN_TYPE_ENUM: any = {
    SUSPEND: '暂停发货',
    VIOLATION: '违规',
    OTHER: '其他',
  }
  private PLAN_TYPE_ENUM: any = {
    0: '计划内',
    1: '计划外',
  }
  private dataSource: DataSourceItem[] = this.props.dataSource
  private planType: number = this.props.planType
  private frozenStatus: number =
    this.planType === 0 ? this.dataSource[0].frozenStatus : this.dataSource[0].frozenStatusWay
  public cRef = createRef<any>()
  constructor(props) {
    super(props)
    this.state = {
      workFlowList: [],
      checkPerson: [],
      values: {},
      loading: false,
      pagination: {
        current: 1,
        pageSize: 5,
        total: this.dataSource.length ?? 0,
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '20', '30', '40'],
        showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
      },
      isApprove: {
        quotaFreeze: false,
      },
    }
  }

  componentDidMount() {
    let params = {
      brandCode: this.dataSource[0]['brandCode'],
      prodBarcode: [...new Set(this.dataSource.map(item => item.prodBarcode))].join(','),
    }
    http.get(todoApi.getProcessKeyFlow, { params }).then(res => {
      this.setState(
        {
          isApprove: res.data,
        },
        () => {
          if (res?.data?.quotaFreeze) {
            this.getWorkFlow()
          }
        }
      )
    })
    this.setState({
      values: {
        planTypeText: this.PLAN_TYPE_ENUM[this.planType],
        frozenStatusText: this.frozenStatus === 0 ? '冻结' : '解冻',
      },
    })
  }
  private onOk = e => {
    this.form.validateFields((err, values) => {
      if (!err) {
        let { isApprove } = this.state
        if (isApprove?.quotaFreeze && this.state.checkPerson.length === 0) {
          message.warn('请选择审批人')
          return false
        }
        e.drawerBtnLoading()
        let ids = this.dataSource.map(({ id, idWay }) => (this.planType === 0 ? id : idWay)).join(',')
        let formValues = this.form.getFieldsValue()
        delete formValues.frozenStatusText
        delete formValues.planTypeText
        const params = {
          ids,
          brandCode: this.dataSource[0]?.brandCode,
          brandName: this.dataSource[0]?.brandName,
          frozenStatus: this.frozenStatus === 0 ? 1 : 0,
          ...formValues,
        }
        if (this.frozenStatus === 1) {
          params['frozenType'] = this.dataSource[0]?.frozenType
        }
        if (this.state.checkPerson.length > 0) {
          params['workflowReqVos'] = {
            name: 'candidateUsers',
            userId: [this.state.checkPerson[0].id],
          }
        }
        http
          .post(quotaApis.batchFreeze, params)
          .then(res => {
            this.props.refresh()
            message.success('操作成功')
            e.close()
          })
          .catch(() => {
            e.drawerBtnLoadingHide()
          })
      } else {
        console.log(err)
      }
    })
  }

  //获取审批角色
  private getWorkFlow = () => {
    http.get(todoApi.getFreezeNextApprove, { params: { brandCode: this.dataSource[0]['brandCode'] } }).then(res => {
      const { data } = res
      this.setState({ workFlowList: data })
    })
  }

  //选择审批人
  private handShowQuotaApprove(index) {
    this.cRef.current.handelCeck(index)
  }

  private handGetPerson(value) {
    this.setState({ checkPerson: value })
  }

  render() {
    let { isApprove } = this.state
    const items = [
      {
        label: '申请类型',
        id: 'frozenStatusText',
        render: <Input readOnly />,
      },
      {
        label: '计划类型',
        id: 'planTypeText',
        render: <Input readOnly />,
      },
      {
        label: '冻结原因',
        id: 'frozenType',
        rules: [validators.required],
        render: (
          <Select>
            <Option value="SUSPEND">暂停发货</Option>
            <Option value="VIOLATION">违规</Option>
            <Option value="OTHER">其他</Option>
          </Select>
        ),
      },
      { label: '备注信息', id: 'remark', render: <TextArea rows={3} /> },
      {
        label: '凭证附件',
        id: 'quotaApplyDetailFileRespVoList',
        render: <UdUploader form={this.form} extra="支持扩展名：.jpg .png .xls .doc" />,
      },
    ]
    const columns = [
      {
        title: '序号',
        dataIndex: 'id',
        key: 'id',
        width: 50,
        render: (text, record, index) => index + 1,
      },
      { title: '客户编码', dataIndex: 'dealerCode' },
      { title: '客户名称', dataIndex: 'dealerName' },
      { title: '品牌公司', dataIndex: 'brandName' },
      { title: '配额品项', dataIndex: 'prodBarname' },
      { title: '考核年度', dataIndex: 'stageYear', width: 80 },
      {
        title: '考核阶段',
        dataIndex: 'stageName',
        width: 80,
        render: (text, record) => {
          return (
            <Tooltip title={record.stageName}>
              <div style={{ width: '80px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                {record.stageName}
              </div>
            </Tooltip>
          )
        },
      },
      {
        title: '冻结原因',
        dataIndex: 'frozenType',
        render: (text, record, index) => {
          return this.FROZEN_TYPE_ENUM[record.frozenType]
        },
      },
    ]
    return (
      <>
        <UdTable
          rowKey="id"
          columns={
            this.frozenStatus === 1
              ? columns
              : columns.filter(item => {
                  return item.dataIndex !== 'frozenType'
                })
          }
          dataSource={this.dataSource}
          onChange={pagination => {
            this.setState({ pagination })
          }}
          pagination={this.state.pagination}
        />
        <div>&nbsp;</div>
        <UdForm
          getForm={form => (this.form = form)}
          items={
            this.frozenStatus === 0
              ? items
              : items.filter(item => {
                  return item.id !== 'frozenType'
                })
          }
          values={this.state.values}
        />
        {isApprove?.quotaFreeze && <h4>审批流程</h4>}
        {isApprove?.quotaFreeze && (
          <div className="approve-wrap">
            <div className="node-name-wrap">
              <div className="title">节点名称：</div>
              <span className="circle-point"></span>
              <div>{this.state.workFlowList[0]?.nodeName || '暂无'}</div>
            </div>
            <div className="person-name-wrap">
              <div className="title">审批人:</div>
              <div
                className={this.state.checkPerson[0]?.realName ? 'add-plus-name' : 'add-plus'}
                onClick={() => {
                  this.handShowQuotaApprove(0)
                }}
              >
                {this.state.checkPerson[0]?.realName || '+'}
              </div>
            </div>
          </div>
        )}
        <QuotaApprove
          handCilck={this.handGetPerson.bind(this)}
          cRef={this.cRef}
          ids={this.state.workFlowList[0]?.roleIds}
        />
      </>
    )
  }
}

interface IProps {
  planType: number
  selectedRowKeys?: number[] | string[]
  dataSource?: any
  refresh?: any
  isApprove?: any
}
interface IState {
  isApprove?: any
  dataSource?: any
  values: any
  loading: boolean
  page?: number
  size?: number
  total?: number
  pagination?: any
  workFlowList?: any[]
  checkPerson?: any[]
}
